package com.ysjy.course.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.input.XmlStreamReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;

@Slf4j
public class XmlUtils {

	public static String ConverObjectToString(Object obj) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			OutputStream os = new ByteArrayOutputStream();
			OutputStreamWriter writer = new OutputStreamWriter(os);
			jaxbMarshaller.marshal(obj, writer);
			return os.toString();
		} catch (JAXBException e) {
			e.printStackTrace();
//			throw new BusinessException(ErrorConstants.ERROR_JAXB_EXCEPTION, e);
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> Object stringToObject(String value, Class<T> c) {
		JAXBContext jc;
		try {
			jc = JAXBContext.newInstance(c);
			Unmarshaller unmarshaller = jc.createUnmarshaller();
			InputStream is;
			try {
//				String getString = value.replace((char) 0x00a0, ' ');// 转换特殊字符
				is = new ByteArrayInputStream(value.getBytes("UTF-8"));
				XmlStreamReader reader = null;
				reader = new XmlStreamReader(is);
				return (T) unmarshaller.unmarshal(reader);
			} catch (UnsupportedEncodingException e1) {
				log.error(e1.getStackTrace().toString());
				e1.printStackTrace();
//				throw new BusinessException(
//						ErrorConstants.ERROR_UNSUPPORTED_ENCODING_EXCEPTION);
			} catch (IOException e) {
				log.error(e.getStackTrace().toString());
				e.printStackTrace();
//				throw new BusinessException(ErrorConstants.ERROR_IO_EXCEPTION);
			}
		} catch (JAXBException e) {
			log.error(e.getStackTrace().toString());
			e.printStackTrace();
//			throw new BusinessException(ErrorConstants.ERROR_JAXB_EXCEPTION);
		} catch (Exception e) {
			log.error(e.getStackTrace().toString());
			e.printStackTrace();
//			throw new BusinessException(ErrorConstants.ERROR_UNKNOWN_EXCEPTION);
		}
		return null;
	}
	
}
